<html>
<head>
<#assign basePath=request.contextPath>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>基础模块-轮播管理-新增</title>
<#include "/WEB-INF/views/template/bootMainCss.ftl" parse=true encoding="utf-8">
    <!-- bootstrap-datetimepicker -->
    <link href="${basePath}/bootstrap/plugin/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css" rel="stylesheet">
    <link rel="stylesheet" href="${basePath}/bootstrap/css/jquery.treegrid.css">
    <link href="${basePath}/bootstrap/css/form.lzy.css" rel="stylesheet">
    <link href="${basePath}/bootstrap/css/good.lzy.css" rel="stylesheet">
    <style>
        .add-check label{ padding-top: 5px;}
        .add-check input{ height: auto;}
        .add-check span{ position: relative; padding: 0 30px 0 10px;}
    </style>
</head>
<body>
<input id="p_add"  value="1" type="hidden">
<input id="p_update"  value="1" type="hidden">
<div class="panel panel-f5">
    <div class="panel-body row">
        <form id="myForm" class="form-horizontal"  method="post" action="${basePath}/activity/save"  enctype="multipart/form-data">
            <input type="hidden" id="_ctx" value="${basePath}"/>
            <input type="hidden" name="id" id="id" value="${carousel.id!}">
            <input type="hidden" name="token" value="${token!}" />

            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 类型：</span>
                <div id="wrap" class="col-sm-9 col-xs-8">
                    <label>
                    <#if carousel.id == null>
                        <input class="fixed wrap1" type="radio" name="type" value="1" checked="checked" /> <span style="margin-left: 10px">平台链接-海报轮播</span>
                        <input class="hid hid1 wrap2" type="radio" name="type" value="2" style="margin-left: 30px" /><span style="margin-left: 10px">图片详情-海报轮播</span>
                        （请选择轮播内容类型）
                    </#if>
                    <#if carousel.id != null>
                        <#if carousel.type==1>
                            <span style="display: block; margin-top: 5px;">平台链接-海报轮播</span>
                            <input type="hidden" name="type" value="1">
                        </#if>
                        <#if carousel.type==2>
                            <span style="display: block; margin-top: 5px;">图片详情-海报轮播</span>
                            <input type="hidden" name="type" value="2">
                        </#if>
                    </#if>
                    </label>
                </div>
            </div>
            <div class="form-group group1">
                <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 所属板块：</span>
                <div class="col-sm-9 col-xs-8">
                    <select id="sourceType" name="sourceType" class="form-control required">
                        <option value="">请选择所属板块</option>
                    <#if typeList != null>
                        <#list typeList as type>
                            <option value="${type.code!}"<#if carousel.sourceType == type.code>selected</#if>></option>
                        </#list>
                    </#if>
                    </select>
                    （请选择轮播产品所属板块）
                </div>
            </div>
            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 轮播图片：</span>
                <div class="col-sm-9 col-xs-8">
                <#if carousel==null || carousel.url==null  || carousel.url==''>
                    <input class="obj-input" name="url" value="" type="text">
                    <img class="obj-img" src="" style="display:none" width="100" height="100">
                    <span class="input-file">
                            <input type="file" data-action="goods" data-image="url" onchange="uploadImg(this)">
                        </span>
                </#if>
                <#if carousel!=null && carousel.url!=null  && carousel.url!=''>
                    <input class="obj-input" name="url" value="${carousel.url!}" type="text">
                    <img class="obj-img" src="${carousel.url!}" width="150" height="100">
                    <span class="input-file-edit">
                            <input id="" type="file" data-action="goods" data-image="url" onchange="uploadImg(this)">
                        </span>
                </#if>
                    （请上传轮播图显示在首页页头750px*405px，3M以内）
                </div>
            </div>
            <div class="form-group group2">
                <span class="control-label col-sm-2 col-xs-4">轮播详情图：</span>
                <div class="col-sm-9 col-xs-8">
                <#if carousel.detail==null  || carousel.detail==''>
                    <input class="obj-input" name="detail" value="" type="text">
                    <img class="obj-img" src="" style="display:none" width="100" height="100">
                    <span class="input-file">
                         <input type="file" data-action="goods" data-image="detail" onchange="uploadImg(this)">
                    </span>
                </#if>
                <#if carousel!=null && carousel.detail!=null  && carousel.detail!=''>
                    <input class="obj-input" name="detail" value="${carousel.detail!}" type="text">
                    <img class="obj-img" src="${carousel.detail!}" width="150" height="100">
                    <span class="input-file-edit">
                         <input type="file" data-action="goods" data-image="detail" onchange="uploadImg(this)">
                    </span>
                    <div class="add-inputfile add-inputfile1">
                        <i class="fa fa-plus"></i>
                    </div>
                </#if>
                    （请上传轮播详情图750px*高度不限，建议：您切图之后上传，3M以内）
                </div>
            </div>
            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 轮播名称：</span>
                <div class="col-sm-9 col-xs-8">
                    <input type="text" class="form-control" size="30" name="name" id="name" maxlength="50" value="${carousel.name!}">
                    （请填写轮播名，在后台显示区分轮播，限制50字）
                </div>
            </div>
            <div class="form-group carousel-box group1">
                <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 轮播链接地址：</span>
                <div class="col-sm-9 col-xs-8">
                    <input type="text" class="form-control" size="30" name="path" id="path" maxlength="95" value="${carousel.path!}" data-url="" readonly>
                    <span id="carousel-btn">获取轮播链接地址</span>
                    （请选择轮播推广的产品/活动/线路）
                </div>
            </div>
            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 排序：</span>
                <div class="col-sm-9 col-xs-8">
                    <input type="text" class="form-control" size="30" name="sort" id="sort" maxlength="5" value="${carousel.sort!}">
                    （请选择轮播播放顺序）
                </div>
            </div>

            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4"></span>
                <div class="col-sm-9 col-xs-8">
                    <button type="button" class="btn btn-success" onclick="submitForm();"><i class="fa fa-check"></i> 确定</button>
                    <button type="button" class="btn btn-info" onclick="closePage();"><i class="fa fa-close"></i> 关闭</button>
                <#--（查看上传后的样式案例）<span class="viewImg" onclick="viewImg(this)" title="${basePath}/bootstrap/images/miniApp/carousel_view.jpg"></span>-->
                </div>
            </div>
        </form>
    </div>
</div>

<div class="super-bg">
    <div class="super-box">
        <h3>选择商品<i class="fa fa-close"></i></h3>
        <div class="super-tit">
            搜索：
            <input class="text" type="text" name="rotationKey" value="" placeholder="商品名称/商家名称">
            <input class="submit" type="submit" value="搜索" onclick="reSearch(1,this.name)">
        <#--<%--<button type="button" class="btn btn-success"><i class="fa fa-check"></i> 确定</button>--%>-->
        </div>
        <div class="panel-body panel-white">
            <div class="table-responsive">
                <table width="95%" border="0" align="center"
                       id="myTable"
                       class="table table-hover"
                       data-pageSize="10,50,100" data-method="GET">
                    <thead>
                    <tr>
                        <th width="10%">序号</th>
                        <th width="25%">商品名称</th>
                        <th width="25%">商家名称</th>
                        <th width="25%">价格</th>
                        <th width="15%">操作</th>
                    </tr>
                    </thead>
                    <tbody id="tbodyId">

                    </tbody>
                </table>
            </div>
            <div class="row">
                <div align="left" class="col-xs-4">
                    <div class="input-group">
                        <span class="input-group-addon" id="pageCount"></span> <select
                            id="pageSize" onchange="reSearch(1)" class="form-control"
                            style="width: 100px"></select>
                    </div>
                </div>
                <div align="right" class="col-xs-8">
                    <ul class="pagination" id="pagination"></ul>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="good-add-suc">
    <span>
        <b>操作成功</b>
        该页面将在 5 秒后自动跳转！
        <a href="${basePath}/appletCarousel/page" target="_parent">返回列表</a>
    </span>
</div>

<#include "/WEB-INF/views/template/bootMainJs.ftl" parse=true encoding="utf-8">
<!-- bootstrap-datetimepicker -->
<script type="text/javascript" src="${basePath}/bootstrap/plugin/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="${basePath}/bootstrap/plugin/bootstrap-datetimepicker/bootstrap-datetimepicker.zh-CN.js"></script>
<!-- ajaxfileupload -->
<script	src="${basePath}/bootstrap/plugin/ajaxfileupload/ajaxfileupload.js" type="text/javascript"></script>
<script type="text/javascript" src="${basePath}/bootstrap/js/jquery.treegrid.js"></script>
<script src="${basePath}/bootstrap/plugin/jqPaginator/jqPaginator.js" type="text/javascript"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script>
<script type="text/javascript">
    $(window).bootstrapValidator || document.write('<script src="${basePath}/bootstrap/js/bootstrapValidator.min.js"><\/script>');
</script>
<script type="text/javascript">
    function viewImg(obj){
        var _this = "<img src='"+obj.title+"' style='max-height: 100%'>";
        layer.open({
            type: 1,
            title: false,
            area: ['auto', '90%'],
            content: _this,
            end: function(){
                layer.closeAll();
            }
        })
    }
    //2017-5-23
    $(function(){

        //轮播类型
        $(".group2").hide();
        $("#wrap input").change(function(){
            if($(this).val() == 2){
                $(".group1").hide();
                $(".group2").show();
            }
            else{
                $(".group2").hide();
                $(".group1").show();
            }
        })
        if($("input[name='type']").val() == 2){
            $(".group1").hide();
            $(".group2").show();
        }
        else{
            $(".group2").hide();
            $(".group1").show();
        }



        var btn = $("#carousel-btn");
        btn.hide();
        var sourceType = $("#sourceType");
        var ajaxUrl,imgUrl;
        //删除系统首页选项
        sourceType.find("option").each(function(){
            if($(this).val() == "0" && $(this).html() == "小程序首页"){
                $(this).remove();
            }
        });
        sourceType.change(function(){
            btn.show();
            $(".carousel-box").show();
            document.getElementById("path").value="";
            var n = parseInt($(this).val());
            switch(n)
            {
                case 0://小程序首页
                    ajaxUrl = "";
                    imgUrl = "";
                    btn.hide();
                    $(".carousel-box").hide();
                    break;
                case 1://推荐线路
                    ajaxUrl = "${basePath}/appletLine/json?shelves=1&status=0";
                    imgUrl = "${basePath}/api/appletLine/detail/";
                    break;
                case 2://活动推广
                    ajaxUrl = "${basePath}/appletActivity/json?shelves=1&status=0";
                    imgUrl = "${basePath}/api/appletActivity/detail/";
                    break;
                case 3://旅行装备
                    ajaxUrl = "${basePath}/appletItem/json?shelves=1&status=0";
                    imgUrl = "${basePath}/api/appletItem/detail/";
                    break;
            }
            $("#path").attr("data-url",imgUrl);
            $(".submit").attr("name",ajaxUrl);
            var myTh = $("#myTable th");
            //周边项目
            if($(this).val() == "5"){
                myTh.eq(1).html("企业名称").next().html("所在城市").next().html("会员");
                $("input[name='rotationKey']").attr("placeholder","企业名称");
                $(".super-tit input").eq(0).attr("name","name");
            }
            else{
                myTh.eq(1).html("商品名称").next().html("商家名称").next().html("价格");
                $("input[name='rotationKey']").attr("placeholder","商品名称/商家名称");
                $(".super-tit input").eq(0).attr("name","rotationKey");
            }
        });
        //click事件放到change外
        btn.click(function(){
            //初始化下拉框
            $("#pageSize").empty();
            var data = $('#myTable').attr('data-pageSize').split(',');
            for(var i=0;i<data.length;i++) {
                var option = $("<option>").text(data[i]).val(data[i]);
                $("#pageSize").append(option);
            }
            //定义查询选择框
            $.jqPaginator('#pagination', {
                totalPages: 100,
                visiblePages: 10,
                currentPage: 1,
                first: '<li class="first"><a href="javascript:void(0);">首页<\/a><\/li>',
                prev: '<li class="prev"><a href="javascript:void(0);">上一页<\/a><\/li>',
                next: '<li class="next"><a href="javascript:void(0);">下一页<\/a><\/li>',
                last: '<li class="last"><a href="javascript:void(0);">末页<\/a><\/li>',
                page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
                onPageChange: function (num,type) {
                    type = ajaxUrl;
                    reSearch(num,type);
                }
            });
        });

    });

    var priceUnit = "元";
    function reSearch(pageNum,type){
        var $spbox = $(".super-bg");
        var $tbody = $(".super-box table tbody");
        $spbox.show();
        $tbody.html("");

        var category = $("#category");
        var myTh = $("#myTable th");
        if(category.val() == "3"){
            priceUnit = "万元";
        }
        category.change(function(){
            //积分商城
            if($(this).val() == "7"){
                priceUnit = "龙珠";
            }
            //房车销售
            else if($(this).val() == "3"){
                priceUnit = "万元";
            }
            else{
                priceUnit = "元";
            }
            //周边项目
            if($(this).val() == "5"){
                myTh.eq(1).html("企业名称").next().html("所在城市").next().html("会员");
                $("input[name='rotationKey']").attr("placeholder","企业名称");
                $(".super-tit input").eq(0).attr("name","name");
            }
            else{
                myTh.eq(1).html("商品名称").next().html("商家名称").next().html("价格");
                $("input[name='rotationKey']").attr("placeholder","商品名称/商家名称");
                $(".super-tit input").eq(0).attr("name","rotationKey");
            }
        });

        //加载层
        layer.load(2);
        //获取form表单传入参数
        var jsonData ={};

        jsonData.begin = (pageNum-1) * $('#pageSize').val();
        jsonData.rows = $('#pageSize').val();
        //计算当前页面
        jsonData.pageNum = pageNum;
        jsonData.pageSize = jsonData.rows;

        //搜索赋值
        var $spText = $(".super-tit input.text");
        var rotationKey = $spText.attr("name");
        jsonData[rotationKey] = $spText.val();

        //获取数据
        $.ajax({
            type:"GET",
            url:type,
            dataType:"json",
            async:"true",
            data:jsonData,
            success:function(data){
                layer.closeAll('loading');
                $('#pageCount').html('当前总记录数:' + data.total);//显示记录数
                if(data.total > 0){
                    //计算页数
                    if(data.total%$('#pageSize').val() > 0){
                        var pageCount = (data.total - data.total%$('#pageSize').val())/$('#pageSize').val() + 1;
                    }else{
                        var pageCount = data.total/$('#pageSize').val();
                    }

                    $('#pagination').jqPaginator('option', {
                        currentPage: pageNum, //当前页数
                        totalPages: pageCount //总页数
                    });

                    //拼接显示数据
                    var rows = data.rows;
                    var temp = "";
                    for(var i in rows){
                        if(rows[i].price == null){
                            rows[i].price = 0
                        }
                        //周边项目
                        if(category.val() == "5"){
                            if(rows[i].cityName == null){
                                temp += "<tr><td style='display: none'>"+rows[i].id+"</td><td width='10%'>"+(parseInt(i)+1)+"</td>" +
                                        "<td width='25%'>"+rows[i].name+"</td>" +
                                        "<td width='25%'>"+rows[i].proName+"</td>" +
                                        "<td width='25%'>"+rows[i].contact +"</td>" +
                                        "<td width='15%'><a href='#'>选择</a></td></tr>"
                            }else{
                                temp += "<tr><td style='display: none'>"+rows[i].id+"</td><td width='10%'>"+(parseInt(i)+1)+"</td>" +
                                        "<td width='25%'>"+rows[i].name+"</td>" +
                                        "<td width='25%'>"+rows[i].proName+"-"+rows[i].cityName+"</td>"
                                        +"<td width='25%'>"+rows[i].contact +"</td>" +
                                        "<td width='15%'><a href='#'>选择</a></td></tr>"
                            }
//                            temp += "<tr><td style='display: none'>"+rows[i].id+"</td><td width='10%'>"+(parseInt(i)+1)+"</td>" +
//                                    "<td width='25%'>"+rows[i].name+"</td>" +
//                                    if(rows[i].cityName == null){
//                                        "<td width='25%'>"+rows[i].proName+"</td>"
//                                    }else{
//                                        "<td width='25%'>"+rows[i].proName+"-"+rows[i].cityName+"</td>"
//                                    }
//                                    +"<td width='25%'>"+rows[i].contact +"</td>" +
//                                    "<td width='15%'><a href='#'>选择</a></td></tr>"
                        }
                        else{
                            temp += "<tr><td style='display: none'>"+rows[i].id+"</td><td width='10%'>"+(parseInt(i)+1)+"</td>" +
                                    "<td width='25%'>"+rows[i].name+"</td>" +
                                    "<td width='25%'>"+rows[i].shopName+"</td>" +
                                    "<td width='25%'>"+rows[i].price +" "+ priceUnit +"</td>" +
                                    "<td width='15%'><a href='#'>选择</a></td></tr>"
                        }
                    }
                    $tbody.append(temp);
                    ChooseVal();
                }else{
                    $('#pageCount').html('当前总记录数:0');//显示记录数
                    $('#pagination').jqPaginator('option', {
                        currentPage: 1, //当前页数
                        totalPages: 1 //总页数
                    });
                    $("#tbodyId").html('<tr align="center"><td colspan="' + $("#myTable").find("th").length + '">未查询到匹配的数据</td><tr>');
                }

                //设置统计结果
                if(typeof data.curPage != 'undefined'){
                    var cur = data.curPage;
                    for(var o in cur){
                        $("#"+o+"_cur").text(cur[o]);
                    }
                }
                //设置统计结果
                if(typeof data.allPage != 'undefined'){
                    var cur = data.allPage;
                    for(var o in cur){
                        $("#"+o+"_all").text(cur[o]);
                    }
                }

            },
            error:function(){
                console.log("error")
                //关闭加载层
                layer.closeAll('loading');
                $('#pageCount').html('当前总记录数:0');//显示记录数
                $("#tbodyId").html('<tr align="center"><td colspan="' + $("#myTable").find("th").length + '">未查询到匹配的数据</td><tr>');
            }
        });
        //关闭按钮
        $(".super-box .fa-close").click(function(){
            $spbox.hide();
            $tbody.html("");
            $(".super-tit input.text").val("");//清空搜索
        });

    };
    //选择函数
    function ChooseVal(){
        var $sptr = $(".super-box table tbody tr");
        var $spbox = $(".super-bg");
        var $tbody = $(".super-box table tbody");
        $sptr.each(function(){
            $(this).find("td:last").click(function(event){
                event.preventDefault();
                var $spval = $(this).parent().find("td");
                var $path = $("#path");
                //设置值
                $path.val($path.attr("data-url") + $spval.eq(0).html()).change();
                $spbox.hide();
                $tbody.html("");
                $(".super-tit input.text").val("");
            })
        })
    }

    //获取图片路径
    function getPath(obj, fileQuery, transImg) {
        var imgSrc = '',
                imgArr = [],
                strSrc = '';
        if (navigator.appName == "Microsoft Internet Explorer"&&parseInt(navigator.appVersion.split(";")[1].replace(/[ ]/g, "").replace("MSIE",""))<=9) { // IE浏览器判断
            alert("您的浏览器版本过低，请下载IE10及以上版本或者谷歌、火狐等主流浏览器");
        } else {
            var file = fileQuery.files[0];
            var reader = new FileReader();
            reader.onload = function (e) {

                imgSrc = fileQuery.value;
                imgArr = imgSrc.split('.');
                strSrc = imgArr[imgArr.length - 1].toLowerCase();
                if (strSrc.localeCompare('jpg') === 0 || strSrc.localeCompare('jpeg') === 0 || strSrc.localeCompare('gif') === 0 || strSrc.localeCompare('png') === 0) {
                    obj.setAttribute("src", e.target.result);
                } else {
                    throw new Error('File type Error! please image file upload..');
                }
            }
            reader.readAsDataURL(file);
        }
    }
    //图片显示
    function show(img,tp){
        var file_img=document.getElementById(img),
                iptfileupload= document.getElementById(tp) ;
        getPath(file_img,iptfileupload,file_img) ;
    }
    var action="${action}";
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    //关闭窗口并刷新页面
    function closePage() {
        parent.layer.close(index);
    }
    function submitForm() {
        var bsVal = $("#myForm").data('bootstrapValidator');
        bsVal.validate();
        if(bsVal.isValid()){
            $.ajax({
                method : 'POST',
                dataType: 'json',
                url:  '${basePath}/appletCarousel/'+action ,
                data: $("#myForm").serialize(),
                success: function (data) {
                    if(data.code == '0000' || data.code == '0'){
                        layer.open({
                            type: 1,
                            title: false,
                            content: $(".good-add-suc"),
                            area: ['600px', '300px'],
                            time: 5000,
                            end: function(){
                                parent.layer.closeAll();
                                window.location.href = '${basePath}/appletCarousel/page';
                            }
                        });
                    }else{
                        layer.alert(data.desc, {
                            icon : 5
                        });
                    }
                },
                error: function(){
                    layer.alert('系统错误', {
                        icon : 5
                    });
                }
            });
        }
        else{
            var smallTop = $("small:visible").eq(0).offset().top - 50;
            $("html,body").animate({scrollTop:smallTop},300);
        }
    }

    $('#myForm').bootstrapValidator({
        //excluded:[":disabled"],
        fields: {
            sourceType: {
                validators: {
                    notEmpty: {
                        message: '请选择所属板块'
                    }
                }
            },
            type: {
                validators: {
                    notEmpty: {
                        message: '请选择类型'
                    }
                }
            },
            url: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请上传轮播图片'
                    }
                }
            },
//            detail: {
//                trigger:"change",
//                validators: {
//                    notEmpty: {
//                        message: '请上传轮播详情图片'
//                    }
//                }
//            },
            name: {
                validators: {
                    notEmpty: {
                        message: '请输入轮播名称'
                    }
                }
            },
            path: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择轮播链接地址'
                    }
                }
            },
            sort: {
                validators: {
                    notEmpty: {
                        message: '请输入排序'
                    },
                    regexp: {
                        regexp: regInt,
                        message: '请输入数字'
                    }
                }
            }
        }
    });
    //新增上传框
    $('.add-inputfile1').on('click',function(){
        addImg('tourPhotoWallDTOList',this);
    });
    var tourPhotoWallDTOIndex =1;
    function addImg(name1,obj){
        var str1 = "<div class='inputfile-img-box'><input class='obj-input' name="+name1+"["+tourPhotoWallDTOIndex+"].url  value='' type='hidden'>" +
                "<img class='obj-img' src='' style='display:none' width='100' height='100'><span class='input-file'>" +
                "<input data-image="+name1+"["+tourPhotoWallDTOIndex+"].url data-action='goods' type='file' onchange='uploadImg(this)'></span><i class='fa fa-close'></i></div>";
        var len = $(obj).parent().find(".inputfile-img-box").length;
        tourPhotoWallDTOIndex ++;
//        if(len < 4){
//            $(obj).before(str1);
//        }
//        else{
//            return false
//        }
        $("i.fa-close").click(function(){
            $(this).parent().remove();
        });

</script>
</body>
</html>